<template>
<div>
  <n-card :segmented="{ content: 'hard' }" :bordered="false" size="small" >
   <n-grid cols="1" responsive="screen" :x-gap="24" style="margin-left: 15px">
      <n-gi :span="1">
          <n-space>
            <n-button type="info" icon-placement="left" @click="addDept">
              添加子部门
              <template #icon>
                <div class="flex items-center">
                  <n-icon size="14">
                    <MdAdd />
                  </n-icon>
                </div>
              </template>
            </n-button>
            <n-button type="default"  icon-placement="left" @click="addRootDept">
              添加一级部门
              <template #icon>
                <div class="flex items-center">
                  <n-icon size="14">
                    <IosAdd />
                  </n-icon>
                </div>
              </template>
            </n-button>
            <n-button type="error" ghost icon-placement="left" @click="removeDept">
              批量删除
              <template #icon>
                <div class="flex items-center">
                  <n-icon size="14">
                    <IosTrash />
                  </n-icon>
                </div>
              </template>
            </n-button>
            <n-button type="default" icon-placement="left" @click="refreshData">
              刷新
              <template #icon>
                <div class="flex items-center">
                  <n-icon size="14">
                    <IosRefresh />
                  </n-icon>
                </div>
              </template>
            </n-button>
          </n-space>
      </n-gi>
    </n-grid>
   <n-grid class="mt-4" :cols="4" responsive="screen" :x-gap="24" style="margin-left: 15px">
    <n-gi :span="1">
      <n-grid :cols="1" y-gap="8">
        <n-alert type="info" size="small"> 当前选择编辑：
          <span style="color: #40a9ff;">{{selectTitle}}</span>
          <a style="margin-left: 10px" v-if="selectTitle!=''" @click="cancelSelect">取消选择</a>
        </n-alert>
        <n-input type="input" v-model:value="pattern" placeholder="输入部门名称搜索">
          <template #suffix>
            <n-icon size="18" class="cursor-pointer">
              <IosSearch />
            </n-icon>
          </template>
        </n-input>
        <div class="py-3 menu-list">
          <template v-if="loading">
            <div class="flex items-center justify-center py-4">
              <n-spin size="medium" />
            </div>
          </template>
          <template v-else>
            <n-tree
              block-line
              multiple
              :virtual-scroll="true"
              :pattern="pattern"
              :data="deptData"
              style="max-height: 650px; overflow: hidden"
              @update:selected-keys="selectedTree"
            />
          </template>
        </div>
      </n-grid>
    </n-gi>
     <n-gi :span="2">
       <n-form
         :model="formData"
         :rules="rules"
         ref="editFormRef"
         label-placement="left"
         :label-width="100"
         class="py-4"
       >
         <n-form-item label="上级部门" path="parentId">
           <n-tree-select :options="editTreeData" v-model:value="formData.parentId"/>
         </n-form-item>
         <n-form-item label="部门名称" path="name">
           <n-input placeholder="请输入部门名称" v-model:value="formData.name" />
         </n-form-item>
         <n-form-item label="排序" path="sort" >
           <n-input-number v-model:value="formData.sort" :min="1"/>
         </n-form-item>
         <n-form-item label="是否启用" path="status" >
           <n-space>
             <n-switch v-model:value="formData.status" />
           </n-space>
         </n-form-item>
         <n-form-item label="备注" path="remark">
           <n-input
             v-model:value="formData.remark"
             type="textarea"
             placeholder="备注"
           />
         </n-form-item>
         <n-form-item path="auth" style="margin-left: 100px">
           <n-space>
             <n-button type="primary" :loading="submitLoading" @click="submitEditForm"
             >提交</n-button
             >
             <n-button @click="handleReset">重置</n-button>
           </n-space>
         </n-form-item>
       </n-form>
     </n-gi>
  </n-grid>
    <n-drawer v-model:show="showForm" :width="500" placement="right" @update:show="clearForm">
      <n-drawer-content :title="drawerTitle" closable>
        <n-form
          :model="addForm"
          :rules="addRules"
          ref="addFormRef"
          label-placement="left"
          :label-width="100"
          class="py-4"
        >
          <n-form-item label="上级部门" path="parentId" v-if="showParent">
            <n-tag type="info"> {{addForm.parentName}} </n-tag>
          </n-form-item>
          <n-form-item label="部门名称" path="name">
            <n-input placeholder="请输入部门名称" v-model:value="addForm.name" />
          </n-form-item>
          <n-form-item label="排序" path="sort" >
            <n-input-number v-model:value="addForm.sort" :min="1"/>
          </n-form-item>
          <n-form-item label="是否启用" path="status" >
            <n-space>
              <n-switch v-model:value="addForm.status" />
            </n-space>
          </n-form-item>
          <n-form-item label="备注" path="remark">
            <n-input
              v-model:value="addForm.remark"
              type="textarea"
              placeholder="备注"
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space>
            <n-button type="primary" :loading="addLoading" @click="submitForm"
            >保存</n-button
            >
            <n-button @click="handleClose">关闭</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </n-card>
</div>
</template>

<script lang="ts">
import {defineComponent,ref,onMounted} from 'vue';
import {getDeptTreeData,saveDept,updateDept,deleteDept,} from "@/api/system/dept";
import { IosAdd,IosTrash, IosSearch,IosRefresh,MdAdd } from '@vicons/ionicons4';
import {useMessage,useDialog} from 'naive-ui'
import { getTreeItem } from '@/utils';
import {deleteUser} from "@/api/system/user";

export default defineComponent({
  name: "Dept",
  components:{
    IosAdd,
    IosTrash,
    IosSearch,
    IosRefresh,
    MdAdd
  },
  setup(){
    let formData=ref({});
    let submitLoading=ref(false);
    let expandedKeys=ref([]);
    let selectedKeys=ref([]);
    let deptData=ref([]);
    let loading=ref(false);
    let editFormRef=ref(null)
    let pattern=ref('');
    let selectTitle=ref('');
    const message=useMessage();
    const dialog=useDialog();
    let editTreeData=ref([]);
    let showForm=ref(false);
    let addForm=ref({});
    let addFormRef=ref(null);
    let drawerTitle=ref('');
    let addLoading=ref(false);
    let showParent=ref(false);
    const rules={
      parentId:{required:true,message:'请选择上级部门',trigger:['change','blur']},
      name:{required:true,message:'请输入部门名称',trigger:['change','blur']},
      sort:{type:'number',required:true,message:'请输入排序',trigger:['change','blur']},
      status:{type:'boolean',required:true,message:'请选择是否启用',trigger:['change','blur']}
    }
    const addRules={
      name:{required:true,message:'请输入部门名称',trigger:['change','blur']},
      sort:{type:'number',required:true,message:'请输入排序',trigger:['change','blur']},
      status:{type:'boolean',required:true,message:'请选择是否启用',trigger:['change','blur']}
    }
    function submitEditForm(){
      editFormRef.value.validate((errors:boolean)=>{
        if(!errors){
          updateDept(formData.value).then(res=>{
            if(res){
              message.success('修改成功');
              submitLoading.value=false;
              initDeptData();
            }
          })
        }else{
          message.error('提交失败')
        }
      })
    }
    function handleReset(){
      clearEditForm();
    }
    function selectedTree(keys){
      let treeItem = getTreeItem(deptData.value,keys[0]);
      formData.value.id=treeItem.deptId;
      formData.value.name=treeItem.label;
      formData.value.parentId=treeItem.parentId;
      formData.value.sort=treeItem.sort;
      formData.value.status=treeItem.status;
      formData.value.remark=treeItem.remark;
      addForm.value.parentName=treeItem.label;
      addForm.value.parentId=treeItem.deptId;
      selectTitle.value=treeItem.label;
      selectedKeys.value=keys;
    }
    function submitForm() {
      addFormRef.value.validate((errors:boolean)=>{
        if(!errors){
          saveDept(addForm.value).then(res=>{
            if(res){
              message.success('添加成功');
              showForm.value=false;
              initDeptData();
              clearForm();
            }
          })
        }else{
          message.error('提交失败')
        }
      })
    }
    function handleClose() {
      clearForm();
    }
    function cancelSelect(){
      selectTitle.value=''
    }
    function refreshData(){
      initDeptData()
    }
    function removeDept(){
      if(selectedKeys.value.length<=0){
        message.warning('请选择您要删除的数据');
        return;
      }
      dialog.warning({
        title: '警告',
        content: '你确定要删除所选的'+selectedKeys.value.length+'条数据吗?删除后无法恢复',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick:()=>{
          const ids = selectedKeys.value.join(",");
          deleteDept(ids).then(res=>{
            if(res){
              message.success('删除成功');
              initDeptData()
              selectedKeys.value=[];
              clearEditForm();
              selectTitle.value='';
            }else{
              message.error(res.message)
            }
          })
        },
        onNegativeClick: () => {
        }
      })

    }
    function addDept(){
      if(addForm.value.parentId==null||addForm.value.parentId==''){
          message.warning('请选择上级部门');
          return;
      }
      showParent.value=true;
      drawerTitle.value='添加子部门'
      showForm.value=true;
    }
    function clearEditForm() {
      Object.keys(formData.value).forEach((key)=>{
        formData.value[key]=null;
      })
    }
    function addRootDept(){
      addForm.value.parentId=0;
      showParent.value=false;
      drawerTitle.value='添加一级'
      showForm.value=true;
    }
    function clearForm(){
      addLoading.value=false;
      Object.keys(addForm.value).forEach((key)=>{
        addForm.value[key]=null;
      })
      showForm.value=false;
    }
    function initDeptData(){
       getDeptTreeData().then(data=>{
         deptData.value=data;
         editTreeData.value=data;
       })
    }
    onMounted(async ()=>{
      initDeptData()
    })
    return {
      formData,
      submitLoading,
      rules,
      expandedKeys,
      selectedKeys,
      deptData,
      loading,
      pattern,
      editFormRef,
      selectTitle,
      editTreeData,
      showForm,
      drawerTitle,
      addForm,
      addRules,
      addLoading,
      addFormRef,
      showParent,
      submitEditForm,
      handleReset,
      selectedTree,
      cancelSelect,
      refreshData,
      removeDept,
      addDept,
      addRootDept,
      clearForm,
      submitForm,
      handleClose
    }
  }
})
</script>

<style scoped>

</style>
